<?php
declare(strict_types=1);
namespace app\admin\model;
use aphp\core\Model;
class Article extends Model
{
	protected string $table = 'article';
	protected string $pk = 'id';
    protected array $validate = [
        ['title', 'required|unique', '标题必须|标题已存在', IF_MUST, AC_BOTH],
        ['url', 'url', '请输入正确的链接', IF_VALUE, AC_BOTH],
        ['markdown', 'required', '请输入内容', IF_MUST, AC_BOTH],
    ];
    protected array $auto = [
        ['summary', 'getSummary', 'method', IF_EMPTY, AC_BOTH],
        ['is_password', 'isPassword', 'method', IF_MUST, AC_BOTH],
        ['status', '1', 'string', IF_MUST, AC_INSERT],
    ];

    public function getSummary(string $val, array $data): string
    {
        $content = clear_html($data['html']);
        return str_substr($content, 86);
    }

    public function isPassword(string $val, array $data): int
    {
        return empty($data['password'])? 0 : 1;
    }

    protected function _before_insert(array &$data): void
    {
        $data['user_id'] = session('user.id');
        $data['author'] = session('user.nickname');
        if (is_array($data['tag_ids'])) {
            $data['tag_ids'] = implode(',', $data['tag_ids']);
        }
    }

    protected function _before_update(array &$data): void
    {
        if ($data['is_auto_summary'] == 1) {
            $data['summary'] = $this->getSummary('', $data);
        }
        if (is_array($data['tag_ids'])) {
            $data['tag_ids'] = implode(',', $data['tag_ids']);
        }
    }

    protected function _before_delete(array $data): void
    {
        $this->db = $this->db->where('status=0');
    }
}